package com.goldcn.user.controller;

import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.dao.OrganizationalMapper;
import com.goldcn.user.dao.UserInfoMapper;
import com.goldcn.user.dto.OrganizationalMoreDto;
import com.goldcn.user.dto.OrganizationalSelectDto;
import com.goldcn.user.model.Organizational;
import com.goldcn.user.model.UserInfo;
import com.goldcn.user.service.ErpInterfaceService;
import com.goldcn.user.service.OrganizationalService;
import com.goldcn.user.service.RedisService;
import com.goldcn.util.RSAUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 1111 on 2016/11/8.
 */
@Api(value = "组织架构")
@RestController
@RequestMapping(value = "/organizational")
public class OrganizationalController {
    @Autowired
    OrganizationalService organizationalService;

    @Autowired
    OrganizationalMapper organizationalMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    RedisService redisService;


    @Autowired
    ErpInterfaceService erpInterfaceService;

    private Logger logger = Logger.getLogger(OrganizationalController.class);

    @ApiOperation(value = "新增架构")
    @RequestMapping(method = RequestMethod.POST)
    public Object addOrganizational(@RequestBody OrganizationalMoreDto organizational) throws Exception {
        PrivateKey key = (PrivateKey) redisService.loadKey(organizational.getRasId());
        byte[] en_result = RSAUtils.hexStringToBytes(organizational.getPassWord());
        byte[] de_result = RSAUtils.decrypt(key, en_result);
        StringBuffer sb = new StringBuffer();
        sb.append(StringUtils.newStringUtf8(de_result));
        organizational.setPassWord(sb.reverse().toString());

        return organizationalService.addOrganizational(organizational);
    }

    @ApiOperation(value = "新增架构:2018")
    @RequestMapping(value = "/gzbank", method = RequestMethod.POST)
    public Object addOrganizationalForNewVersion(@RequestBody OrganizationalMoreDto organizational) throws Exception {
        return organizationalService.addOrganizationalForNewVersion(organizational);
    }

    @ApiOperation(value = "修改架构:2018")
    @RequestMapping(value = "/modify/gzbank", method = RequestMethod.POST)
    public Object updateOrganizationalForGz(@RequestBody OrganizationalMoreDto organizational) throws Exception {
        return organizationalService.updateOrganizationalForGz(organizational);
    }

    @ApiOperation(value = "修改用户资料:2018")
    @RequestMapping(value = "/modify/user", method = RequestMethod.POST)
    public Object updateOrganizationalForGz(@RequestBody UserInfo userInfo) throws Exception {
        return organizationalService.updateUserInfo(userInfo);
    }

    @ApiOperation(value = "修改用户资料:2018 更改是否店长时候检查  1表示该店铺已有店长，0表示没有")
    @RequestMapping(value = "/modify/check", method = RequestMethod.POST)
    public Object updateShopBossForCheck(@RequestBody UserInfo userInfo) throws Exception {
        return organizationalService.updateShopBossForCheck(userInfo);
    }


    @ApiOperation(value = "修改架构")
    @RequestMapping(method = RequestMethod.PUT)
    public Object updateOrganizational(@RequestBody Organizational organizational) {
        return organizationalService.updateOrganizational(organizational);
    }

    @ApiOperation(value = "根据ID查询架构[包含上级路径]")
    @RequestMapping(value = "/getPath/{oID}", method = RequestMethod.GET)
    public Object selectOrganizationalMore(@PathVariable Long oID) throws Exception {
        return organizationalService.selectOrganizationalMore(oID);
    }

    @ApiOperation(value = "根据ID查询架构")
    @RequestMapping(value = "/{oID}", method = RequestMethod.GET)
    public Object selectByOID(@PathVariable Long oID) {
        return organizationalService.selectByOID(oID);
    }

    @ApiOperation(value = "删除架构")
    @RequestMapping(value = "/{oID}", method = RequestMethod.DELETE)
    public Object deleteOrganizational(@PathVariable Long oID, HttpServletRequest request) {
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
//                .getRequestAttributes()).getRequest();
        Organizational organizational = organizationalMapper.selectByPrimaryKey(oID);
        organizationalService.deleteOrganizational(oID);
        try {
            int i = (int) erpInterfaceService.deleteOrgErp(oID + "");
            if (i == 1) {
                logger.info("调用修改架构成功--ERP");
            } else {
                logger.info("调用修改架构成功--ERP");
            }
        } catch (Exception e) {
            logger.info("修改架构调用erp失败,失败架构是:" + organizational.getOrganizationalName() + "---" + organizational.getoID());
        }
        logger.info("准备删除架构:删除架构的ip地址是" + this.getIpAddress(request));
        return "success";
    }


    @ApiOperation(value = "获取下级银行信息列表[仅获取下一级]")
    @RequestMapping(value = "/subBankList/{oID}/{pageNum}/{pageSize}", method = RequestMethod.GET)
    public Object selectSubBankList(@PathVariable Long oID, @PathVariable int pageNum, @PathVariable int pageSize) {
        return organizationalService.selectSubBankList(oID, pageNum, pageSize);
    }

    @ApiOperation(value = "获取下级银行信息列表[仅获取下一级]")
    @RequestMapping(value = "/subBankListV2/{oID}/{pageNum}/{pageSize}", method = RequestMethod.GET)
    public Object selectSubBankListV2(@PathVariable Long oID, @PathVariable int pageNum, @PathVariable int pageSize) {
        return organizationalService.selectSubBankListV2(oID, pageNum, pageSize);
    }


    @ApiOperation(value = "搜索所有下级银行信息列表")
    @RequestMapping(value = "/searchBankList/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Object selectBankSearchList(@RequestBody OrganizationalSelectDto selectDto, @PathVariable int pageNum, @PathVariable int pageSize) {
        return organizationalService.selectBankSearchList(selectDto, pageNum, pageSize);
    }

    @ApiOperation(value = "根据ID查询name的list")
    @RequestMapping(value = "/branchList", method = RequestMethod.POST)
    public Object selectBranchList(@RequestBody List<Long> list) {
        List<Map<String, Object>> mapList = organizationalMapper.selectNameListByOID(list);
        Map<String, Object> resultMap = new HashMap<>();
        if (mapList.size() > 0) {
            for (Map<String, Object> map : mapList) {
                resultMap.put(map.get("oID").toString() + "_level", map.get("level"));
                resultMap.put(map.get("oID").toString(), map.get("organizationalName"));
            }
        }

        for (Long oId : list) {
            List<Organizational> orgList = organizationalMapper.getHasNextOrg(oId);
            Organizational organizational = organizationalMapper.selectByPrimaryKey(oId);
            if (organizational != null) {
                String orgPath = organizationalService.pathName(organizational);
                resultMap.put(oId + "_path", orgPath);
            }
            if (orgList != null && orgList.size() > 0) {
                resultMap.put(oId + "_hasNext", "1");
            } else {
                resultMap.put(oId + "_hasNext", "0");
            }
        }
        return resultMap;
    }


    @ApiOperation(value = "根据ID查询name的list")
    @RequestMapping(value = "/branchListAllState", method = RequestMethod.POST)
    public Object selectBranchListAllState(@RequestBody List<Long> list) {
        List<Map<String, Object>> mapList = organizationalMapper.selectNameListByOIDAllState(list);
        Map<String, Object> resultMap = new HashMap<>();
        if (mapList.size() > 0) {
            for (Map<String, Object> map : mapList) {
                resultMap.put(map.get("oID").toString() + "_level", map.get("level"));
                resultMap.put(map.get("oID").toString(), map.get("organizationalName"));
            }
        }

        for (Long oId : list) {
            List<Organizational> orgList = organizationalMapper.getHasNextOrgAllState(oId);
            Organizational organizational = organizationalMapper.selectByPrimaryKey(oId);
            if (organizational != null) {
                String orgPath = organizationalService.pathName(organizational);
                resultMap.put(oId + "_path", orgPath);
            }
            if (orgList != null && orgList.size() > 0) {
                resultMap.put(oId + "_hasNext", "1");
            } else {
                resultMap.put(oId + "_hasNext", "0");
            }
        }
        return resultMap;
    }

    @ApiOperation(value = "查询银行的名字和级别")
    @RequestMapping(value = "/bankNameLevel/{oID}", method = RequestMethod.GET)
    public Object selectBankNameLevel(@PathVariable Long oID) {
        Organizational organizational = organizationalService.selectByOID(oID);
        Map<String, Object> resultMap = new HashMap<>();
        if (organizational != null) {
            resultMap.put("oName", organizational.getOrganizationalName());
            resultMap.put("level", organizational.getLevel());
        }
        return resultMap;
    }

    /**
     * 得到一个人的组织Id以及组织名字
     *
     * @param oID
     * @return
     */
    @ApiOperation(value = "查询销售经理所在的组织以及组织id")
    @RequestMapping(value = "/orderSalesManager/{oID}", method = RequestMethod.GET)
    public Object selectOrgUserInfo(@PathVariable Long oID) {
        Map<String, Object> map = new HashMap<>();
        if (oID == 1) {
            Organizational org = organizationalMapper.getLevel1Org(SystemContext.getCompanyID());
            map.put("orgId", org.getoID() + "");
            map.put("orgName", org.getOrganizationalName());
            map.put("businessUserId", "");
            map.put("businessUserName", "");
        } else {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(oID);
            Organizational org = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
            map.put("orgId", org.getoID() + "");
            map.put("orgName", org.getOrganizationalName());
            map.put("businessUserId", userInfo.getUserID());
            map.put("businessUserName", userInfo.getName());
        }
        return map;
    }

    /**
     * 得到一个人的组织Id以及组织名字
     *
     * @param oID
     * @return
     */
    @ApiOperation(value = "查询销售经理所在的组织以及组织id")
    @RequestMapping(value = "/orderSalesManagerUser/{oID}/{userId}", method = RequestMethod.GET)
    public Object selectOrgUserInfo(@PathVariable Long oID, @PathVariable Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserInfo buyerUser = userInfoMapper.selectByPrimaryKey(userId);
        if (oID == 1) {
            Organizational org = organizationalMapper.getLevel1Org(SystemContext.getCompanyID());
            map.put("orgId", org.getoID() + "");
            map.put("orgName", org.getOrganizationalName());
            map.put("businessUserId", "");
            map.put("businessUserName", "");
            map.put("buyNumber", buyerUser.getAccount());
        } else {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(oID);
            Organizational org = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
            map.put("orgId", org.getoID() + "");
            map.put("orgName", org.getOrganizationalName());
            map.put("businessUserId", userInfo.getUserID());
            map.put("businessUserName", userInfo.getName());
            map.put("buyNumber", buyerUser.getAccount());
        }
        return map;
    }


    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    //===========create by zll 2017/5/25
    @ApiOperation(value = "根据名字查询某个组织下的组织")
    @RequestMapping(value = "/selectOrgByLikeName/{organizationalId}/{searchName}", method = RequestMethod.GET)
    public Object getOrgListByOrgName(@PathVariable Long organizationalId, @PathVariable String searchName) throws Exception {
        return organizationalService.getOrgIDListByName(organizationalId, searchName);
    }

    @ApiOperation(value = "根据名字查询某个组织下的组织以及等级信息")
    @RequestMapping(value = "/selectOrgMapByLikeName/{organizationalId}/{searchName}", method = RequestMethod.GET)
    public Object getOrgMapByOrgName(@PathVariable Long organizationalId, @PathVariable String searchName) throws Exception {
        return organizationalService.getOrgIdLevelLikeName(organizationalId, searchName);
    }

    @ApiOperation(value = "查询总部")
    @RequestMapping(value = "/getTopOrganizational/{companyID}", method = RequestMethod.GET)
    public Object getTopOrganizational(@PathVariable Long companyID) {
        return organizationalService.selectTopDept(companyID);
    }


    @ApiOperation(value = "查询合伙人下的商城.2018")
    @RequestMapping(value = "/queryMall/{companyID}", method = RequestMethod.GET)
    public Object getOrganizationalMall(@PathVariable Long companyID) {
        return organizationalService.getMallInfo(companyID);
    }

    @ApiOperation(value = "查询商城的合伙人资料.2018")
    @RequestMapping(value = "/queryOrginfo/{shopID}", method = RequestMethod.GET)
    public Object getOrgInfoByMallShopID(@PathVariable Long shopID) {
        return organizationalService.getOrgInfoByMallShopID(shopID);
    }
}
